import React, { useState, useEffect, useReducer} from "react";
import { initState, reducer } from "../Login/user";
import { reqShopList, reqcartedit, reqShopDelete } from "../../http/api";
import { NavBar, Icon } from "antd-mobile";
import "./shop.less";
import { Toast } from "antd-mobile";
import yes from "../../assets/img/yes.webp";
import no from "../../assets/img/no.webp";
export default function Shop(props) {
  // const [state] = useReducer(reducer, initState);
  const [cart, setCart] = useState([]);
  const [allChecked, setAllChecked] = useState(false);
  const state = JSON.parse(sessionStorage.getItem("info"))
 
  // 首先先定义一个变量isRequest ,默认是true
  let isRequest = true;
  useEffect(() => {
    reqList();
  }, []);


  const reqList = async () => {
    let res = await reqShopList({ uid: state.uid });
    if (res.data.code === 200) {
      let arr1 = res.data.list[0].content ? res.data.list[0].content : [];
      let arr2 = res.data.list[1].content ? res.data.list[1].content : [];
      let arr = arr1.concat(arr2);
      arr.forEach((item) => {
        let obj = cart.find((i) => i.id == item.id);
        item.checked = obj ? obj.checked : false;
      });
      setCart(arr);
      // 打开开关
      isRequest = true;
    }
  };
  // 4.点了某一个的checked
  const changeOne = (index) => {
    cart[index].checked = !cart[index].checked;
    //修改cart
    setCart([...cart]);
    //修改allChecked
    setAllChecked(cart.every((item) => item.checked));
  };

  // 5.修改了全选
  const changeAll = () => {
    let newAll = !allChecked;
    //修改全选
    setAllChecked(newAll);
    //修改cart
    cart.forEach((item) => {
      item.checked = newAll;
    });
    setCart([...cart]);
  };

  //6.数量自增
  const add = async (id) => {
    let res = await reqcartedit({ id, type: 2 });
    if (res.data.code == 200) {
      // 修改成功之后，重新请求列表数据
      reqList();
    }
  };

  //7.数量自减少
  const sub = async (id, num) => {
    if (num <= 1) {
      Toast.info("宝贝不能再少了",1);
      return;
    }
    //判断开关是否打开，开着，就发请求
    if (isRequest) {
      // 开关关掉
      isRequest = false;
      let res = await reqcartedit({ id, type: 1 });
      if (res.data.code == 200) {
        // 修改成功之后，重新请求列表数据
        reqList();
      }
    }
  };
  const delect = async (id) => {
    let res = await reqShopDelete({ id });
    if (res.data.code === 200) {
      Toast.info(res.data.msg,1);
      reqList();
    }
  };
  // 直接计算总价
  let allPrice = cart.reduce(
    (val, item) => (item.checked ? (val += item.price * item.num) : val),
    0
  );
  return (
    <div className="shop">
      <NavBar
        mode="light"
        icon={<Icon type="left" />}
        onLeftClick={() => {
          props.history.go(-1);
        }}
      >
        购物车
      </NavBar>
      <ul className="nav">
        <li>全部({})</li>
        <li>降价({})</li>
        <li>常卖</li>
        <li>分类</li>
      </ul>
      {cart.map((item, index) => (
        <div key={item.id} className="item">
          <div className="chekced" onClick={() => changeOne(index)}>
            {item.checked ? (
              <div>
                <img src={yes} alt="" />
              </div>
            ) : (
              <div>
                <img src={no} alt="" />
              </div>
            )}
          </div>
          <div className="right">
            <div className="imger">
              <img src={item.img} alt="" />
            </div>
            <div>
              <h4>{item.goodsname}</h4>
              <div>price:{item.price}</div>
              <div>
                <button onClick={() => sub(item.id, item.num)}>-</button>
                {item.num}
                <button onClick={() => add(item.id)}>+</button>
              </div>
              <button
                onClick={() => {
                  delect(item.id);
                }}
              >
                删除
              </button>
            </div>
          </div>
        </div>
      ))}

      {/* 全选 */}
      <div className="chekced2 chekced" onClick={() => changeAll()}>
        {allChecked ? (
          <div>
            全选
            <img src={yes} alt="" />
          </div>
        ) : (
          <div>
            全选 <img src={no} alt="" />
          </div>
        )}
      </div>

      {/* 总价 */}
      <div className="chekced2">总价：{allPrice}</div>
    </div>
  );
}
